package com.zshan.clinic.common.util.desensitization;


public class Desensitization {

    /** 133****5678（前3后4） */
    public static String maskMobile(String s) {
        if (s == null || s.length() < 7) {
            return s;
        }
        return s.replaceAll("(\\d{3})\\d{4}(\\d+)", "$1****$2");
    }

    /** 4601**********123X（前4后4） */
    public static String maskIdCard(String s) {
        if (s == null || s.length() < 8) {
            return s;
        }
        return s.replaceAll("^(.{6}).*(.{4})$", "$1**********$2");
    }

    /** 王* / 张**（中文名简单示例） */
    public static String maskName(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        if (s.length() == 1) {
            return "*";
        }
        if (s.length() == 2) {
            return s.charAt(0) + "*";
        }
        return s.charAt(0) + repeat("*", s.length() - 2) + s.charAt(s.length() - 1);
    }

    /** a***@xxx.com */
    public static String maskEmail(String s) {
        if (s == null || !s.contains("@")) {
            return s;
        }
        String[] parts = s.split("@", 2);
        String left = parts[0];
        if (left.length() <= 1) {
            return "*" + "@" + parts[1];
        }
        return left.charAt(0) + "***@" + parts[1];
    }

    /** 自定义保留：keepLeft/keepRight */
    public static String maskKeep(String s, int keepLeft, int keepRight) {
        if (s == null) {
            return null;
        }
        if (s.length() <= keepLeft + keepRight) {
            return s;
        }
        return s.substring(0, keepLeft)
                + repeat("*", s.length() - keepLeft - keepRight)
                + s.substring(s.length() - keepRight);
    }

    private static String repeat(String s, int n) {
        StringBuilder sb = new StringBuilder(n);
        for (int i = 0; i < n; i++) {
            sb.append(s);
        }
        return sb.toString();
    }

    public static void main(String[] args) {

        System.out.println(maskEmail("371081483@qq.com"));
    }

}

